package wms

import (
	"context"
	"encoding/json"
	"ez/apps/wms/auto/mc"
	"gitee.com/dreamwood/ez-go/db/mgo"
	"gitee.com/dreamwood/ez-go/ez"
	"gitee.com/dreamwood/ez-go/ss"
	"time"
)

type AttributeKey struct {
	mgo.BaseDoc `bson:"-" json:"-"`
	Id          int64             `json:"id" bson:"id,omitempty"`
	Name        string            `json:"name" bson:"name"`     //名称
	Code        string            `json:"code" bson:"code"`     //编码
	Note        string            `json:"note" bson:"note"`     //说明
	Values      []*AttributeValue `json:"values" bson:"values"` //值
	CreateAt    time.Time         `json:"createAt" bson:"createAt"`
	UpdateAt    time.Time         `json:"updateAt" bson:"updateAt"`
	DeleteAt    *time.Time        `json:"deleteAt" bson:"deleteAt"`
}

func (this *AttributeKey) DocName() string { return "AttributeKey" }
func (this *AttributeKey) GetId() int64    { return this.Id }
func (this *AttributeKey) SetId(id int64)  { this.Id = id }
func (this *AttributeKey) Create() error {
	return this.GetFactory().Create(this)
}
func (this *AttributeKey) Replace() error {
	return this.GetFactory().Replace(this)
}
func (this *AttributeKey) Save() error {
	if this.Id == 0 {
		this.CreateAt = time.Now()
		this.UpdateAt = time.Now()
		return this.GetFactory().Create(this)
	} else {
		this.UpdateAt = time.Now()
		return this.GetFactory().Replace(this)
	}
}

// 伪删除
func (this *AttributeKey) Delete() error {
	return this.GetFactory().Delete(this)
}
func (this *AttributeKey) UnDelete() error {
	return this.GetFactory().UnDelete(this)
}

// 真删除
func (this *AttributeKey) Destroy() error {
	return this.GetFactory().Destroy(this)
}
func (this *AttributeKey) ToString() string {
	return string(this.ToBytes())
}
func (this *AttributeKey) ToBytes() []byte {
	data, e := json.Marshal(this)
	ez.Try(e)
	return data
}
func (this *AttributeKey) Serialize() []byte {
	data, e := json.Marshal(this)
	ez.Try(e)
	return data
}
func (this *AttributeKey) UnSerialize(data []byte) []byte {
	ez.Try(json.Unmarshal(data, this))
	return data
}
func (this *AttributeKey) LoadValues() {
	values, _ := NewAttributeValueCrud().FindBy(ss.M{"valuesIds": this.Id}, []string{"id"}, 0, 0)
	this.Values = values
}
func (this *AttributeKey) ClearRelationsBeforeSave() mgo.Doc {
	this.Values = nil
	return this
}
func neverUsed_AttributeKey() {
	//导入ss包
	a := ss.M{}
	ez.Debug(a)
}

type AttributeKeyAccessControl struct {
	Access  bool
	Message string
	Action  string //控制器Action,小写开头，如c,u,r,d
	Model   *AttributeKey
	Session *ez.Session
}

func NewAttributeKeyAccessControl(model *AttributeKey, action string, session *ez.Session) *AttributeKeyAccessControl {
	ctrl := &AttributeKeyAccessControl{
		Access:  true,
		Model:   model,
		Action:  action,
		Session: session,
	}
	ez.DispatchToMany(mc.AttributeKeyAccessControlEvent, ctrl, context.TODO())
	return ctrl
}
